package kr.co.pension.usr.bd.mg.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.co.pension.admin.bd.mg.service.BDMGService;
import kr.co.pension.admin.bd.mg.vo.BDMGVo;
import kr.co.pension.admin.co.ma.service.COMAService;
import kr.co.pension.admin.pe.ti.service.PETIService;
import kr.co.pension.admin.pe.ti.vo.PETIVo;
import kr.co.pension.usr.pe.re.service.PEREService;
import kr.co.pension.usr.pe.re.vo.PEREVo;
import kr.co.pension.utils.BaseController;
import kr.co.pension.utils.ConstValue;
import kr.co.pension.utils.JspUtil;
import kr.co.pension.utils.PaginationInfo;
import kr.co.pension.utils.SMCommonUtil;
import kr.co.pension.utils.sms.SMSUtil;
import nl.captcha.Captcha;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/board/bd/mg/*")
public class UBDMGController extends BaseController{
	@Autowired
	private BDMGService service;
	
	@Autowired
	private COMAService comaService;
	
	@Autowired
	private PEREService pereService;
	
	@Autowired
	private PETIService petiService;


	Logger log = Logger.getLogger(getClass());
	
	//파일 업로드 폴더 설정
	private final String FILE_PATH= ConstValue.TOP_UPLOAD+ "/bdmg";
	
	/**
	 * 펜션별 게시판 관리
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ubdmg0101Q(BDMGVo vo,HttpServletRequest req, HttpServletResponse res) throws Exception {
		
//		게시판 속성정보
		Map boardAttr = service.ubdmg0101_1Q(vo);
		
		//게시물이 없다면 에러 표시
		if(boardAttr == null){
			
		}
		
//		// 페이징 시작
		PaginationInfo paginationInfo = new PaginationInfo();
		int currnetPageNo = vo.getCurrentPageNo() <= 1 ? 1 : (Integer) vo
				.getCurrentPageNo();
		
		vo.setCurrentPageNo(currnetPageNo);
		vo.setParamMap(requestPram2Map(req));


		int iTotalCnt = service.ubdmg0101_cntQ(vo);
		vo.setTotalRecordCount(iTotalCnt);
		
		ModelAndView mav = new ModelAndView("board/bd/mg/ubdmg0101Q"+boardAttr.get("brd_type"));
		
		if(iTotalCnt>0){
			
			if("3".equals(boardAttr.get("brd_type"))){
				//사진 게시판일경우
				vo.setRecordCountPerPage(12);
				mav.addObject("list", service.ubdmg0101_3Q(vo));
			}else{
				mav.addObject("list", service.ubdmg0101_2Q(vo));	
			}
			// 상위 코드목록
			
			mav.addObject("pageHtml", vo.getToHtml("./ubdmg0101Q.do"));
			mav.addObject("paginationInfo", vo);
		}
		
		//공지사항 설정
		mav.addObject("noticeList", service.ubdmg0101_4Q(vo));
		
		mav.addObject("boardAttr", boardAttr);
		return mav;
	}
	
	
	/**
	 * 게시판 등록 폼
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ubdmg0102Q(BDMGVo vo,HttpServletRequest req, HttpServletResponse res) throws Exception {
		
//		게시판 속성정보
		Map boardAttr = service.ubdmg0101_1Q(vo);
		ModelAndView mav = new ModelAndView("board/bd/mg/ubdmg0102Q"+boardAttr.get("brd_type"));
		mav.addObject("boardAttr", boardAttr);
		return mav;
	}
	
	/**
	 * 게시판 등록 프로세스
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ubdmg0103T(HttpServletRequest req, HttpServletResponse res,MultipartHttpServletRequest mRqst) throws Exception {
		
		ModelAndView mav = new ModelAndView("/common/close");
		BDMGVo vo = new BDMGVo();

		SMCommonUtil util = new SMCommonUtil();
		util.mapToBean(req.getParameterMap(), vo);
		
		Map usr = (Map) req.getSession().getAttribute("userInfo");
		
		Map boardAttr = service.ubdmg0101_1Q(vo);
		
		if("2".equals(boardAttr.get("brd_type")) || "4".equals(boardAttr.get("brd_type"))){
			//공지 faq는 사용자가 입력 할수 없다
			if(usr==null){
				mav.addObject("msg", "잘못된 접근입니다.");
				mav.addObject("historyBackYn","Y");
				
				return mav;
			}
		}
		
		if(usr == null || usr.get("admin_id") == null || "".equals(usr.get("admin_id"))){
			if(vo.getP_id()== null || usr == null || !vo.getP_id().equals(usr.get("p_id"))){

				Captcha captcha = (Captcha) req.getSession().getAttribute(Captcha.NAME);
				if(vo==null ||  vo.getAnswer()==null ||!captcha.isCorrect(vo.getAnswer())){
					mav.addObject("msg", "입력코드를 확인하세요");
					mav.addObject("historyBackYn","Y");
					
					return mav;
				}
			}
		}
		
		
		
		MultiValueMap mulitFileMap =  mRqst.getMultiFileMap();
		
		
		String[] files = {"file"};
		Map fileMap = util.getFileInfo(mulitFileMap, mRqst.getSession().getServletContext().getRealPath(""),FILE_PATH,false, files);
		
		if("Y".equals((String)fileMap.get("error_yn"))){
			mav.addObject("msg",fileMap.get("error_msg"));
			mav.addObject("historyBackYn","Y");
			return mav;
		}
		
		int bd_no = service.ubdmg0103_1T(vo);
		//파일저장
		List fileList = (List) fileMap.get("file_arr");
		if(fileList!=null){
			for(int i =0; i<fileList.size() ; i++){
				Map fileData = (Map) fileList.get(i);
				fileData.put("bd_no", bd_no);
				service.ubdmg0103_2T(fileData);
			}
		}
		
//		if(null!=fileMap.get("p_logo")){
//			vo.setP_logo((String) fileMap.get("p_logo"));
//		}
		mav.addObject("redirect","./ubdmg0101Q.do?p_id="+vo.getP_id()+"&brd_no="+vo.getBrd_no());
		
		//sms 전송
		if("Y".equals(boardAttr.get("sms_yn")) && usr ==null){
			PETIVo petiVo = new PETIVo();
			petiVo.setP_id(vo.getP_id());
			Map pensionInfo = petiService.peti300Q(petiVo);
			
			SMSUtil smsUtil = new SMSUtil();
			
			String send = pensionInfo.get("p_tel1")+"-"+pensionInfo.get("p_tel2")+"-"+pensionInfo.get("p_tel3");
			String recive = pensionInfo.get("p_phone1")+"-"+pensionInfo.get("p_phone2")+"-"+pensionInfo.get("p_phone3");
			
			String msg = boardAttr.get("brd_nm")+" 게시판에 새글이 입력되었습니다 \n "+vo.getBd_title();
			
			String returnCode = smsUtil.send(send, recive, JspUtil.getByteSizeToString(msg.toString(),80));
//			
//			if("1".equals(returnCode)){
//				//보내기 성공
//				req.getSession().setAttribute("smsChk", msg.toString());
//			}
			PEREVo vo1 = new PEREVo();
			//sms 히스토리에 넣기
			vo1.setP_nm((String) pensionInfo.get("p_nm") );
			vo1.setFrom_no(send);
			vo1.setTo_no(recive);
			vo1.setSms_content(JspUtil.getByteSizeToString(msg.toString(),80));
			vo1.setC_code(returnCode);
			vo1.setC_msg(smsUtil.smsReturnMsg(returnCode));
			vo1.setP_id(vo.getP_id());
			pereService.pere710Q(vo1);
			if("1".equals(returnCode)){
				//sms 카운트 줄이기
				pereService.pere711Q(vo1);
			}
		}
		
		return mav;
	}
	
	
	/**
	 * 게시판 수정 폼
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ubdmg0104Q(BDMGVo vo,HttpServletRequest req, HttpServletResponse res) throws Exception {
		
//		게시판 속성정보
		Map boardAttr = service.ubdmg0101_1Q(vo);
		
		Map brd = service.ubdmg0104Q(vo);
		if(brd==null ){
			ModelAndView mav = new ModelAndView("/common/close");
			mav.addObject("msg","비밀번호와 일치하는 자료가 없습니다.");
			mav.addObject("redirect","./ubdmg0110Q.do?p_id="+vo.getP_id()+"&brd_no="+vo.getBrd_no()+"&bd_no="+vo.getBd_no()+"&type=1");
			
			return mav;
		}
		
		ModelAndView mav = new ModelAndView("board/bd/mg/ubdmg0104Q"+boardAttr.get("brd_type"));
		mav.addObject("boardAttr", boardAttr);
		mav.addObject("fileList", service.ubdmg0107_fileListQ(vo));
		mav.addObject("brd", brd);
		
		return mav;
	}
	
	/**
	 * 게시판 수정 프로세스
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ubdmg0105T(HttpServletRequest req, HttpServletResponse res ,MultipartHttpServletRequest mRqst) throws Exception {

		BDMGVo vo = new BDMGVo();
		
		ModelAndView mav = new ModelAndView("/common/close");
		
		SMCommonUtil util = new SMCommonUtil();
		util.mapToBean(req.getParameterMap(), vo);
		
		Map boardAttr = service.ubdmg0101_1Q(vo);
		Map usr = (Map) req.getSession().getAttribute("userInfo");
		if("2".equals(boardAttr.get("brd_type")) || "4".equals(boardAttr.get("brd_type"))){
			//공지 faq는 사용자가 입력 할수 없다
			if(usr==null){
				mav.addObject("msg", "잘못된 접근입니다.");
				mav.addObject("historyBackYn","Y");
				
				return mav;
			}
		}
		MultiValueMap mulitFileMap =  mRqst.getMultiFileMap();
		
		String[] files = {"file"};
		Map fileMap = util.getFileInfo(mulitFileMap, mRqst.getSession().getServletContext().getRealPath(""),FILE_PATH,false, files);
		
		if("Y".equals((String)fileMap.get("error_yn"))){
			//history back
			mav.addObject("msg",fileMap.get("error_msg"));
			return mav;
		}
		String [] del_bdf_no =  (String[]) req.getParameterMap().get("del_bdf_no");
		
		if(null != del_bdf_no && del_bdf_no.length >0){
			List dList = new ArrayList();
			for(int i=0; i < del_bdf_no.length;i++){
				dList.add(del_bdf_no[i]);
			}
			vo.setList(dList);
			
			//파일삭제
			List delFile = service.ubdmg0105Q(vo);
			
			service.ubdmg0105_1T(vo);
		}
		
		//파일저장
		List fileList = (List) fileMap.get("file_arr");
		if(fileList!=null){
			for(int i =0; i<fileList.size() ; i++){
				Map fileData = (Map) fileList.get(i);
				fileData.put("bd_no", vo.getBd_no());
				service.ubdmg0103_2T(fileData);
			}
		}
		
		int resultCnt = service.ubdmg0105T(vo);
		if(resultCnt==0){
			mav.addObject("msg","비밀번호가 틀립니다.");
			mav.addObject("historyBackYn","Y");
			return mav;	
		}else{
			mav.addObject("msg","수정되었습니다.");
			if("4".equals(boardAttr.get("brd_type"))){
				//faq일 경우 목록으로 이동
				mav.addObject("redirect","./ubdmg0101Q.do?p_id="+vo.getP_id()+"&brd_no="+vo.getBrd_no());	
			}else{
				mav.addObject("redirect","./ubdmg0107Q.do?p_id="+vo.getP_id()+"&brd_no="+vo.getBrd_no() +"&bd_no="+vo.getBd_no());	
			}
			
			return mav;
		}
		
		
		
	}
	
	/**
	 * 게시판 삭제 프로세스
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	@RequestMapping
	public ModelAndView ubdmg0106T(BDMGVo vo,HttpServletRequest req, HttpServletResponse res) throws Exception {
		ModelAndView mav = new ModelAndView("/common/close");
		Map boardAttr = service.ubdmg0101_1Q(vo);
		Map usr = (Map) req.getSession().getAttribute("userInfo");
		if("2".equals(boardAttr.get("brd_type")) || "4".equals(boardAttr.get("brd_type"))){
			//공지 faq는 사용자가 입력 할수 없다
			if(usr==null){
				mav.addObject("msg", "잘못된 접근입니다.");
				mav.addObject("historyBackYn","Y");
				
				return mav;
			}
		}
		
		int resultCnt = service.ubdmg0106_1Q(vo);

		if(resultCnt==0){
			mav.addObject("msg","비밀번호가 틀립니다.");
			mav.addObject("historyBackYn","Y");
			return mav;	
		}else{
			List list = service.ubdmg0106Q(vo);
			
			service.ubdmg0106_1T(vo);
			service.ubdmg0106_2T(vo);
			service.ubdmg0106T(vo);
			
//			파일삭제
			if(list != null && list.size()>0){
				for(int i =0; i < list.size();i++){
					Map data = (Map) list.get(i);
					String filePath = (String) data.get("p_file_nm");
					File delFil = new File(req.getSession().getServletContext().getRealPath(FILE_PATH+filePath));
					if(delFil.isFile()){
						delFil.delete();
					}
				}
			}
			mav.addObject("msg","삭제되었습니다.");
			mav.addObject("redirect","./ubdmg0101Q.do?p_id="+vo.getP_id()+"&brd_no="+vo.getBrd_no());
			return mav;
		}
//		return mav;
	}
	
	/**
	 * 상세수정 조회화면
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ubdmg0107Q(BDMGVo vo,HttpServletRequest req, HttpServletResponse res) throws Exception {
		
//		게시판 속성정보
		Map boardAttr = service.ubdmg0101_1Q(vo);
		ModelAndView mav = new ModelAndView("board/bd/mg/ubdmg0107Q"+boardAttr.get("brd_type"));
		service.ubdmg0107_1Q(vo);
		Map map = service.ubdmg0107Q(vo);
		
		//비밀글인데 비밀번호 없이 조회하는 경우 튕긴다
		if("Y".equals(map.get("secret_yn")) && !map.get("bd_pwd").equals(vo.getBd_pwd())){
			mav = new ModelAndView("/common/close");
			mav.addObject("msg", "비밀번호를 확인하세요");
			mav.addObject("historyBackYn","Y");
			return mav;
		}
		mav.addObject("map", map);
		mav.addObject("cmtList", service.ubdmg0107_cmtListQ(vo));
		mav.addObject("fileList", service.ubdmg0107_fileListQ(vo));
		mav.addObject("boardAttr", boardAttr);
		return mav;
	}
	
	/**
	 * 댓글 등록
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ubdmg0108T(BDMGVo vo,HttpServletRequest req, HttpServletResponse res) throws Exception {
		
		ModelAndView mav = new ModelAndView("/common/close");
		Map usr = (Map) req.getSession().getAttribute("userInfo");
		
		if(usr == null || usr.get("admin_id") == null || "".equals(usr.get("admin_id"))){
			if(vo.getP_id()== null || usr == null || !vo.getP_id().equals(usr.get("p_id"))){

				Captcha captcha = (Captcha) req.getSession().getAttribute(Captcha.NAME);
				if(vo==null ||  vo.getAnswer()==null ||!captcha.isCorrect(vo.getAnswer())){
					mav.addObject("msg", "입력코드를 확인하세요");
					mav.addObject("historyBackYn","Y");
					
					return mav;
				}
			}
		}
		
		service.ubdmg0108T(vo);
		
		
		mav.addObject("msg","등록되었습니다.");
		Map map = service.ubdmg0107Q(vo);
		if("Y".equals(map.get("secret_yn"))){
			mav.addObject("redirect","./ubdmg0107Q.do?p_id="+vo.getP_id()+"&brd_no="+vo.getBrd_no() +"&bd_no="+vo.getBd_no()+"&bd_pwd=" + vo.getBd_pwd());
		}else{
			mav.addObject("redirect","./ubdmg0107Q.do?p_id="+vo.getP_id()+"&brd_no="+vo.getBrd_no() +"&bd_no="+vo.getBd_no());	
		}
//		mav.addObject("redirect","./ubdmg0107Q.do?p_id="+vo.getP_id()+"&brd_no="+vo.getBrd_no() +"&bd_no="+vo.getBd_no());
//		게시판 속성정보
		
		
		return mav;
	}
	
	/**
	 * 댓글 삭제 프로세스
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ubdmg0109T(BDMGVo vo,HttpServletRequest req, HttpServletResponse res) throws Exception {
		
		int cnt = service.ubdmg0109T(vo);
		Map map = service.ubdmg0107Q(vo);
		ModelAndView mav = new ModelAndView("/common/close");
		if(cnt==1){
			mav.addObject("msg","삭제되었습니다.");
		}else{
			mav.addObject("msg","비밀번호와 일치하는 댓글이 없습니다.");

		}
		if("Y".equals(map.get("secret_yn"))){
			mav.addObject("redirect","./ubdmg0107Q.do?p_id="+vo.getP_id()+"&brd_no="+vo.getBrd_no() +"&bd_no="+vo.getBd_no()+"&bd_pwd=" + vo.getBd_pwd());
		}else{
			mav.addObject("redirect","./ubdmg0107Q.do?p_id="+vo.getP_id()+"&brd_no="+vo.getBrd_no() +"&bd_no="+vo.getBd_no());	
		}
		
		
		return mav;
	}
	
	
	/**
	 * 비밀번호 확인페이지
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ubdmg0110Q(BDMGVo vo,HttpServletRequest req, HttpServletResponse res) throws Exception {
		
//		int cnt = service.ubdmg0109T(vo);
		ModelAndView mav = new ModelAndView();

		mav.addObject("map", service.ubdmg0107Q(vo));
		
		return mav;
	}
	
	
	/**
	 * 공지글 변경
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ubdmg0111T(BDMGVo vo,HttpServletRequest req, HttpServletResponse res) throws Exception {
		isMember(req,res);
		if("".equals(vo.getNotice_yn())){	vo.setNotice_yn(null);	}
		int cnt = service.ubdmg0111T(vo);
		ModelAndView mav = new ModelAndView("/common/close");
		if(cnt==1){
			mav.addObject("msg","변경되었습니다.");
		}else{
			mav.addObject("msg","일치하는 데이터가 없습니다.");
		}
		mav.addObject("redirect","./ubdmg0107Q.do?p_id="+vo.getP_id()+"&brd_no="+vo.getBrd_no() +"&bd_no="+vo.getBd_no());
		
		return mav;

	}
	
	@RequestMapping
	public ModelAndView abc(HttpServletRequest req, HttpServletResponse res) throws Exception {
		ModelAndView mav = new ModelAndView();
		String data = req.getParameter("data");
		BufferedWriter file = new BufferedWriter(new FileWriter("/usr/local/apache-tomcat-6.0.35/webapps/ROOT/a.txt", true));
		 
		file.write(data);
		file.newLine();//얘는 String 별로 개행하기 위해
		file.close();
		return mav;

	}
}
